//
//  LMAuthViewController.m
//  李明微博
//
//  Created by 张青花 on 15/12/7.
//  Copyright (c) 2015年 李明. All rights reserved.
//

#import "LMAuthViewController.h"
#import "AFNetworking.h"
#import "LSMessageHUD.h"
#import "LMAccount.h"
#import "LMAccountTool.h"
#import "LMRootTool.h"

#define  APPKEY @"3671842877"
#define  AppSecret @"f38d6f18a8b1632621d564a1b644a61a"
#define  OAuthURl @"https://api.weibo.com/"



@interface LMAuthViewController ()<UIWebViewDelegate>

@end

@implementation LMAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIWebView *webView= [[UIWebView alloc] initWithFrame:self.view.bounds];
    
    [self.view addSubview:webView];
    
    NSString *client_id = APPKEY;
    NSString *redirect_uri = @"http://www.baidu.com";
    
    NSString *urlstr = [NSString stringWithFormat:@"%@oauth2/authorize?client_id=%@&redirect_uri=%@",OAuthURl,client_id,redirect_uri];
    
    NSLog(@"%@",urlstr);
    
    NSURL *url = [NSURL URLWithString:urlstr];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [webView loadRequest:request];
   
    webView.delegate = self;
   
    
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    NSString *urlStr = request.URL.absoluteString;
    
     NSLog(@"urlStr = %@",urlStr);
    
    NSRange range = [urlStr rangeOfString:@"code="];
    
    NSString *code = @"";
    
    if (range.length) {
        code = [urlStr substringFromIndex:range.location +range.length];
        NSLog(@"code = %@",code);
        
        [self accessTokenWithCode:code];
        return NO;
    }
    

    return  YES;
}

- (void)accessTokenWithCode:(NSString *)code
{

    [LMAccountTool accessTokenWithCode:code success:^{
           [LMRootTool setroot:LMKeyWindow];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    
}



- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [LSMessageHUD showWithMessage:@"正在加载"];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView

{
     NSLog(@"222222");
    [LSMessageHUD dismissActiveMessageView];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [LSMessageHUD dismissActiveMessageView];
}




@end
